package co.yixiang.modules.websocket;

/**
 * @Author
 * @Date2020/7/10 17:41
 * @Version V1.0
 **/

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 12450
 * 简书demo：https://www.jianshu.com/p/d79bf8174196
 */
@Slf4j
@ServerEndpoint(value = "/websocket/{userId}")
@Component
public class Websocket {

    /**
     * 与某个客户端的连接对话，需要通过它来给客户端发送消息
     */
    private Session session;

    /**
     * 标识当前连接客户端的用户名
     */
    private String userId;

    /**
     * 用于存所有的连接服务的客户端，这个对象存储是安全的
     */
    private static ConcurrentHashMap<String, Websocket> webSocketSet = new ConcurrentHashMap<>();


    @OnOpen
    public void OnOpen(Session session, @PathParam(value = "userId") String userId) {
        this.session = session;
        this.userId = userId;
        // userId是用来表示唯一客户端，如果需要指定发送，需要指定发送通过userId来区分
        webSocketSet.put(userId, this);
        log.info("[WebSocket] 连接成功，当前连接人数为：={}", webSocketSet.size());
    }


    @OnClose
    public void OnClose() {
        webSocketSet.remove(this.userId);
        log.info("[WebSocket] 退出成功，当前连接人数为：={}", webSocketSet.size());
    }

    @OnMessage
    public void OnMessage(String message) {
        log.info("[WebSocket] 收到消息：{}", message);
        //判断是否需要指定发送，具体规则自定义
//        if (message.indexOf("TOUSER") == 0) {
//            String userId = message.substring(message.indexOf("TOUSER") + 6, message.indexOf(";"));
//            AppointSending(userId, message.substring(message.indexOf(";") + 1, message.length()));
//        } else {
//            GroupSending(message);
//        }
    }

    /**
     * 群发
     *
     * @param message
     */
    public void GroupSending(String message) {
        for (String userId : webSocketSet.keySet()) {
            try {
                webSocketSet.get(userId).session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 指定发送
     *
     * @param userId
     * @param message
     */
    public void AppointSending(String userId, String message) {
        try {
            webSocketSet.get(userId).session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}